<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from '../utils/request'
import { Plus } from '@element-plus/icons-vue'
import baseURL from '../config/baseURL'
import { ElMessage, ElMessageBox } from 'element-plus'


const dishes = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(5)
const loading = ref(false)
const categories = ref([])
const searchName = ref('')
const searchCategoryId = ref('')
const searchStatus = ref('')

/**
 * 查询菜品相关逻辑
 * 
 */
// 查询菜品列表
const fetchDishes = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }
    if (searchName.value.trim()) params.name = searchName.value.trim()
    if (searchCategoryId.value) params.categoryId = searchCategoryId.value
    if (searchStatus.value !== '') params.status = searchStatus.value
    const res = await axios.post('/api/dish/list', params)
    dishes.value = res.data.data.data
    total.value = res.data.data.total
  } catch (e) {
    ElMessage.error('获取菜品列表失败')
  } finally {
    loading.value = false
  }
}

// 分页相关逻辑
const handlePageChange = (newPage) => {
  pageNum.value = newPage
  fetchDishes()
}

// 分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  pageNum.value = 1
  fetchDishes()
}

// 搜索和筛选
const onSearch = () => {
  pageNum.value = 1
  fetchDishes()
}

/**
 * 
 * 新增菜品相关逻辑
 * 
 */
// 提交表单
const addDialogVisible = ref(false)
const addForm = reactive({
  name: '',
  categoryId: null,
  price: null,
  image: '',
  description: ''
})
// 表单验证规则
const addFormRules = {
  name: [{ required: true, message: '请输入菜品名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择菜品分类', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  image: [{ required: true, message: '请上传图片', trigger: 'change' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }]
}
const addFormRef = ref()

// 新增菜品表单赋初值
const onAdd = () => {
  addForm.name = ''
  addForm.categoryId = null
  addForm.price = null
  addForm.image = ''
  addForm.description = ''
  addDialogVisible.value = true
}

// 上传成功回调
const handleUploadSuccess = (response) => {
  if (response.code === 1) {
    addForm.image = response.data
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.message || '图片上传失败')
  }
}

// 提交新增菜品表单
const submitAddForm = () => {
  addFormRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      const res = await axios.post('/api/dish/add', { ...addForm })
      if (res.data.code === 1) {
        ElMessage.success('新增成功')
        addDialogVisible.value = false
        fetchDishes()
      } else {
        ElMessage.error(res.data.message || '新增失败')
      }
    } catch (e) {
      ElMessage.error('新增失败')
    }
  })
}


// 图片上传前校验（可选，限制图片类型和大小）
const beforeUpload = (file) => {
  const isJpgPngGif = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isJpgPngGif) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式图片!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }
  return true
}

// 图片预览（本地路径或服务器路径都可）
const getImagePreview = (url) => {
  // 如果后端返回的是绝对路径，建议处理成可访问的静态资源URL
  // 这里假设后端返回的路径可直接访问，否则需要你自己拼接前缀
  if (url.startsWith('http')) return url
  // 例如：将 D:/upload/xxx.jpg 替换为 http://localhost:8080/upload/xxx.jpg
  // 你可以根据实际情况调整
  const filename = url.split(/[\\/]/).pop()
  return baseURL + '/images/' + filename
}

// 和修改菜品有关逻辑
// 修改菜品表单
const editDialogVisible = ref(false)
const editForm = reactive({
  id: null,
  name: '',
  categoryId: null,
  price: null,
  image: '',
  description: '',
  count: null,
  status: null
})
// 修改菜品表单验证规则
const editFormRules = {
  name: [{ required: true, message: '请输入菜品名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择菜品分类', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  image: [{ required: true, message: '请上传图片', trigger: 'change' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  count: [{ required: true, message: '请输入月售', trigger: 'blur' }],
  status: [{ required: true, message: '请输入状态', trigger: 'blur' }]
}
const editFormRef = ref()

// 修改菜品表单赋初值(回显数据)
const onEdit = (row) => {
  // 回显数据
  Object.assign(editForm, row)
  editDialogVisible.value = true
}

// 修改菜品图片上传成功回调
const handleEditUploadSuccess = (response) => {
  if (response.code === 1) {
    editForm.image = response.data
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.message || '图片上传失败')
  }
}

// 修改菜品表单提交
const submitEditForm = () => {
  editFormRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      const res = await axios.post('/api/dish/update', { ...editForm })
      if (res.data.code === 1) {
        ElMessage.success('修改成功')
        editDialogVisible.value = false
        fetchDishes()
      } else {
        ElMessage.error(res.data.message || '修改失败')
      }
    } catch (e) {
      ElMessage.error('修改失败')
    }
  })
}

/**
 * 
 *  删除菜品相关逻辑
 * 
 */
const onDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除菜品【${row.name}】吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      // 推荐用DELETE，如果后端只支持POST也可以
      const res = await axios.delete(`/api/dish/delete/${row.id}`)
      if (res.data.code === 1) {
        ElMessage.success('删除成功')
        fetchDishes()
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    } catch (e) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消，无需处理
  })
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await axios.get('/api/category/list')
    if (res.data.code === 1) {
      categories.value = res.data.data
    } else {
      ElMessage.error(res.data.message || '获取分类失败')
    }
  } catch (e) {
    ElMessage.error('获取分类失败')
  }
}

// 根据分类ID获取分类名
const getCategoryName = (id) => {
  const cat = categories.value.find(c => c.id === id)
  return cat ? cat.name : id
}

onMounted(() => {
  fetchDishes()
  fetchCategories()
})


</script>

<template>
  <div class="dish-management">
    <h1>菜品管理</h1>
    <div class="content">
      <!-- 搜索和新增 -->
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
        <div>
          <el-input v-model="searchName" placeholder="请输入菜品名称" style="width: 180px; margin-right: 10px;" clearable @keyup.enter="onSearch" />
          <el-select v-model="searchCategoryId" placeholder="全部分类" style="width: 150px; margin-right: 10px;" clearable @change="onSearch">
            <el-option label="全部分类" :value="''" />
            <el-option v-for="cat in categories" :key="cat.id" :label="cat.name" :value="cat.id" />
          </el-select>
          <el-select v-model="searchStatus" placeholder="全部状态" style="width: 120px; margin-right: 10px;" clearable @change="onSearch">
            <el-option label="全部状态" :value="''" />
            <el-option label="起售" :value="1" />
            <el-option label="停售" :value="0" />
          </el-select>
          <el-button type="primary" @click="onSearch">搜索</el-button>
        </div>
        <el-button type="primary" @click="onAdd">新增菜品</el-button>
      </div>
      <!-- 新增菜品弹窗 -->
      <el-dialog v-model="addDialogVisible" title="新增菜品" width="500px">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="90px" @keyup.enter="submitAddForm">
          <el-form-item label="菜品名称" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="菜品分类" prop="categoryId">
            <el-select v-model="addForm.categoryId" placeholder="请选择分类" style="width: 100%">
              <el-option v-for="cat in categories" :key="cat.id" :label="cat.name" :value="cat.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input-number v-model="addForm.price" :min="0" />
          </el-form-item>
          <el-form-item label="图片" prop="image">
            <el-upload class="avatar-uploader" action="http://localhost:8080/upload" :show-file-list="false"
              :on-success="handleUploadSuccess" :before-upload="beforeUpload" name="image">
              <img v-if="addForm.image" :src="getImagePreview(addForm.image)" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
            <div class="form-tip">
              最佳图片尺寸：200x200像素，支持JPG/PNG/GIF格式，大小不超过10MB
            </div>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="addForm.description" type="textarea" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">提交</el-button>
        </template>
      </el-dialog>

      <!-- 修改菜品弹窗 -->
      <el-dialog v-model="editDialogVisible" title="修改菜品" width="500px">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="90px" @keyup.enter="submitEditForm">
          <el-form-item label="菜品名称" prop="name">
            <el-input v-model="editForm.name" />
          </el-form-item>
          <el-form-item label="菜品分类" prop="categoryId">
            <el-select v-model="editForm.categoryId" placeholder="请选择分类" style="width: 100%">
              <el-option v-for="cat in categories" :key="cat.id" :label="cat.name" :value="cat.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input-number v-model="editForm.price" :min="0" />
          </el-form-item>
          <el-form-item label="月售" prop="count">
            <el-input-number v-model="editForm.count" :min="0" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-input-number v-model="editForm.status" :min="0" />
          </el-form-item>
          <el-form-item label="图片" prop="image">
            <el-upload class="avatar-uploader" action="http://localhost:8080/upload" :show-file-list="false"
              :on-success="handleEditUploadSuccess" :before-upload="beforeUpload" name="image">
              <img v-if="editForm.image" :src="getImagePreview(editForm.image)" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
            <div class="form-tip">
              最佳图片尺寸：200x200像素，支持JPG/PNG/GIF格式，大小不超过10MB
            </div>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="editForm.description" type="textarea" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">提交</el-button>
        </template>
      </el-dialog>

      <!-- 菜品列表 -->
      <el-table :data="dishes" v-loading="loading" style="width: 100%" height="calc(100vh - 210px)">
        <el-table-column prop="id" label="ID" width="40" />
        <el-table-column label="图片" width="100">
          <template #default="scope">
            <img v-if="scope.row.image" :src="getImagePreview(scope.row.image)" alt="图片"
              style="width: 60px; height: 60px; object-fit: cover; border-radius: 6px;" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="菜品名称" width="120" />
        <el-table-column prop="description" label="描述" width="200" />
        <el-table-column prop="categoryId" label="菜品分类" width="80">
          <template #default="scope">
            {{ getCategoryName(scope.row.categoryId) }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="100" />
        <el-table-column prop="count" label="月售" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'info' : 'success'">
              {{ scope.row.status === 0 ? '停售' : '起售' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="120">
          <template #default="scope">
            {{ scope.row.createTime ? scope.row.createTime.slice(0, 10) : '' }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="120">
          <template #default="scope">
            {{ scope.row.updateTime ? scope.row.updateTime.slice(0, 10) : '' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button type="primary" size="small" @click="onEdit(scope.row)">修改</el-button>
            <el-button type="danger" size="small" @click="onDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页条 -->
      <el-pagination style="margin-top: 20px; text-align: right" background
        layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="pageSize" :current-page="pageNum"
        @current-change="handlePageChange" @size-change="handleSizeChange" :page-sizes="[5, 10, 20, 50]" />
    </div>
  </div>
</template>
<style scoped>

/*整个菜品管理页面容器的样式*/ 
.dish-management {
  width: 100%;
  padding: 10px;
}

/* 表格内容 */
.el-table .el-table__cell {
  white-space: normal;
  word-break: break-all;
}

/* 内容 */
.content {
  width: 100%;
  background-color: white;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

/* 图片上传 */
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
  border-radius: 6px;
  margin-bottom: 5px;
}

/* 图片上传 */
.avatar-uploader-icon {
  font-size: 32px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}

/* 表单提示 */
.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
  margin-left: 2px;
}
</style>